<?php

/**
 * Image_Controller class will take care all handling for uploading images.
 * @author Ali
 * 
 */
define("MAX_IMAGE_SIZE", 5242880);
define("IT_ALLOWED_IMAGES", "jpg,jpeg,png,bmp,gif");

class FileController {

    public $name;
    public $type;
    public $size;
    public $optimized_name;
    public $errors = array();
    public $file_dir;
    private $temp_path;
    private $image_ext;
    private $webRootfilePath;
    protected $uploaded_dir;
    protected $upload_errors = array(
        UPLOAD_ERR_OK => "No errors",
        UPLOAD_ERR_INI_SIZE => "Image size is exceeding 5 MB",
        UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE",
        UPLOAD_ERR_PARTIAL => "Partial upload",
        UPLOAD_ERR_NO_FILE => "No file",
        UPLOAD_ERR_NO_TMP_DIR => "No temporary directory",
        UPLOAD_ERR_CANT_WRITE => "Can't write to disk",
        UPLOAD_ERR_EXTENSION => "File upload stopped by extension"
    );

    /**
     * 
     * @param $file <p> pass in $_FILE['uploaded_file'] </p>
     * @return boolean
     */
    public function attach_file($file) {
       
//perform error checking on the form paramters
        if (!$file || empty($file) || !is_array($file)) {
            //error: nothing uploaded on wrong argument
            $this->errors[] = "No file was uploaded";
            return false;
        } elseif ($file['error'] != 0) {
            $this->errors[] = $this->upload_errors[$file['error']];
            return false;
        } else {

//set object attributes to the form paramters.
            $this->temp_path = $file['tmp_name'];
            $this->name = basename($file['name']);
            $this->type = $file['type'];
            $this->size = $file['size'];
            $this->image_ext = strtolower(end(explode('.', $this->name)));
            return true;
        }
    }

    /**
     * process_image function is responsible for validating image size.
     * @param userid
     * @param $path
     * @return boolean
     */
    public function process_image($userid, $dir) {

        $this->optimized_name = $this->optimize_file_name($userid);
        $this->webRootfilePath = $this->move_to($dir) . $this->optimized_name;
        //echo  $this->webRootfilePath; 
        /*echo "----".$this->move_to($dir)."----";
        if (!$this->validate_file_size(MAX_IMAGE_SIZE)) {
            $this->errors[] = "Image size is exceeding";
            return false;
        } elseif (!$this->validate_file_type('image') || !$this->validate_img_ext() || !$this->validate_image_header($this->temp_path)) {
            $this->errors[] = "Image type is not valid";
            return false;
        } else { */
            if (!$this->move_file($this->webRootfilePath)) {
                $this->errors[] = "Cannot move an image file";
                return false;
            }
            return true;
    }

    /**
     * validate the image type from its header
     * @return boolean if it is invalid false else true 
     */
    private function validate_image_header($imagePath) {
        $fun = "imagecreatefrom" . (str_replace("jpg", "jpeg", $this->image_ext));
        return @$fun($imagePath) === false ? false : true;
    }

    /**
     * validating name of image
     * @param $extra [optional] <p> add extra bit-identifying image as thumbnail</p>
     * @return string <p> file name </p>
     */
    private function optimize_file_name($userid) {

        $day_time = date("YmdHis");
        $radomstr = $this->generate_rand_string(7);
        $opt_name = $day_time . "_" .$userid . '_' . $radomstr;
        return $opt_name . '.' . $this->image_ext;
    }

    /**
     * validating image extension within the defined allowed types.
     * @return boolean
     */
    private function validate_img_ext() {
        //print_r($this->image_ext);
        if (!in_array($this->image_ext, explode(",", IT_ALLOWED_IMAGES))) {
            return false;
        }
        return true;
    }

    /**
     * validating image size
     * @param $size <p> size in bytes</p>
     * @return boolean
     */
    private function validate_file_size($size) {
        $valid = ($this->size > $size) ? false : true;
        return $valid;
    }

    /**
     * validating image type
     * @param $type <p> expected type of files</p>
     * @return boolean
     */
    private function validate_file_type($desired_type) {
        $file_type = $this->type;
        $type = explode('/', $file_type);
        $valid = ($type[0] == $desired_type) ? true : false;
        return $valid;
    }

    /**
     * moving file after validating to the target path
     * @param $target_path
     * @return boolean 
     */
    private function move_file($target_path) {
        //determine target path

        if (move_uploaded_file($this->temp_path, $target_path)) {
            unset($this->temp_path);   //as file has moved to other location.
            
            return true;
        } else {
            return false;
        }
    }
    
   private function generate_rand_string($length=10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string = '';
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters) - 1)];
    }
    return $string;
    }
    
    private function move_to($director) {
        switch ($director) {
            case 'index_page': return $this->file_dir=IMG_UP;
                break;
           
        }
    }


}
